package timer

import (
	"time"
)

func NewTicker(duration time.Duration, handler func()) (obj *Ticker) {
	obj = &Ticker{}
	obj.duration = duration
	obj.handler = handler
	obj.close = make(chan bool)
	return
}

type Ticker struct {
	duration time.Duration
	ticker   *time.Ticker
	close    chan bool
	start    bool

	handler func()
}

func (e *Ticker) update() {
	if e.handler != nil {
		e.handler()
	}
}

func (e *Ticker) Start() {
	if e.start {
		return
	}
	e.start = true

	e.ticker = time.NewTicker(e.duration)
	e.close = make(chan bool)
	go func() {
		for {
			select {
			case <-e.ticker.C:
				e.update()
			case <-e.close:
				return
			}
		}
	}()
	return
}

func (e *Ticker) Stop() {
	if !e.start {
		return
	}
	e.start = false
	e.close <- true
	e.ticker.Stop()
}

func (e *Ticker) Reset() {
	if e.ticker == nil {
		e.Start()
	} else {
		e.ticker.Reset(e.duration)
	}
}
